//
//  MyDeviceManageController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/10/10.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "MyDeviceManageController.h"
#import "MeSettingDevCtlCell.h"
#import "RoomModel.h"
#import "DeviceEditController.h"
#import "DataManager.h"
#import "ZTLCCamera.h"
//#import "ZTMovableCellTableView.h"
#import "RTDragCellTableView.h"
#import "GlobalConst.h"
@interface MyDeviceManageController ()
<
DataManagerRefreshDelegate,
RTDragCellTableViewDelegate,
RTDragCellTableViewDataSource,
MGSwipeTableCellDelegate
>
@property (nonatomic, strong)RTDragCellTableView *tableView;
@property (nonatomic, strong)NSArray <RoomModel *> *m_roomModels;
@end
static NSString *const MyDeviceManageCellIdentifier = @"MyDeviceManageCellIdentifier";
@implementation MyDeviceManageController

#pragma mark - life cycle
- (void)dealloc
{
    debugLogInfo(@"MyDeviceManageController  dealloc");
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [kDataManager removeRefreshDelegate:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    [self refreshDeviceName];
    [kDataManager addRefreshDelegate:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DataManagerRefreshDelegate
- (void)deviceRefresh:(DataManager*__nonnull)manager callbackType:(DeviceCallbackType)callbackType
{
    if (callbackType == DeviceCallbackTypeName) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshDeviceName];
        });
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.m_roomModels.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.m_roomModels.count > 0)
    {
        return  self.m_roomModels[section].devices.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MeSettingDevCtlCell *cell = [tableView dequeueReusableCellWithIdentifier:MyDeviceManageCellIdentifier];
    if (!cell)
    {
        cell = [[MeSettingDevCtlCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:MyDeviceManageCellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.rightButtons = [self createRightButtons:2];
        cell.delegate = self;
    }
    if (indexPath.row >= self.m_roomModels[indexPath.section].devices.count)
    {
        debugLogInfo(@"row 越界");
    }
    else
    {
        cell.device = self.m_roomModels[indexPath.section].devices[indexPath.row] ;
    }
    return cell;
}

///**
// *  获取tableView的数据源数组
// */
//- (NSArray *)dataSourceArrayInTableView:(ZTMovableCellTableView *)tableView
//{
//    return self.m_roomModels;
//}
///**
// *  返回移动之后调换后的数据源
// */
//- (void)tableView:(ZTMovableCellTableView *)tableView newDataSourceArrayAfterMove:(NSArray *)newDataSourceArray
//{
//    self.m_roomModels = [newDataSourceArray copy];
//}
- (NSArray *)originalArrayDataForTableView:(RTDragCellTableView *)tableView{
    return self.m_roomModels;
}

- (void)tableView:(RTDragCellTableView *)tableView newArrayDataForDataSource:(NSArray *)newArray{
    self.m_roomModels = newArray;
}

#pragma mark - UITableViewDelegate

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
//    if ( self.m_roomModels[section].devices.count > 0 )
//    {
        return self.m_roomModels[section].name;
//    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 26;
}


#pragma mark - MGSwipeTableCellDelegate
-(BOOL)swipeTableCell:(MGSwipeTableCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion
{
    debugLogInfo(@"Delegate: button tapped, %@ position, index %d, from Expansion: %@",
          direction == MGSwipeDirectionLeftToRight ? @"left" : @"right", (int)index, fromExpansion ? @"YES" : @"NO");
    if (direction == MGSwipeDirectionRightToLeft && index == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle: @"你确定要删除此设备？"message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSIndexPath * path = [self.tableView indexPathForCell:cell];
            ZTDevice *device = self.m_roomModels[path.section].devices[path.row] ;
            if ( ![self delDev:device]) {
                return;
            }
            [kMQTTSessionManager deviceDelete:device.apsn Luid:device.luid];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return NO; //Don't autohide to improve delete expansion animation
    }else if (direction == MGSwipeDirectionRightToLeft && index == 1) {
        DeviceEditController *deviceEditVc = [[DeviceEditController alloc]init];
        NSIndexPath * path = [self.tableView indexPathForCell:cell];
        deviceEditVc.device = self.m_roomModels[path.section].devices[path.row];
        deviceEditVc.fromMe = true;
        [self.navigationController pushViewController:deviceEditVc animated:YES];
        return NO;
    }
    
    return YES;
}

#pragma mark - private method
- (void)initSubviews
{
    self.navigationItem.title = @"我的设备管理";
    [self.view addSubview:self.tableView];
    [self layoutPageSubviews];
}
- (void)layoutPageSubviews
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}
- (void)refreshDeviceName
{
    RoomModel *newDevRoom = [[RoomModel alloc]initWithTitle:@"未分房间的设备"];
    NSMutableArray* roomNameLists = [DataManager roomNameLists];
    NSMutableArray* roomDevLists = [NSMutableArray arrayWithCapacity:roomNameLists.count];
    for (NSString* name in roomNameLists) {
        RoomModel *devRoom = [[RoomModel alloc]initWithTitle:name];
        [roomDevLists addObject:devRoom];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (ZTDevice *dev  in kDataManager.deviceListenList )
        {
            if (dev.name.length == 0 || [[dev getRoomName] isEqualToString:@"unknow"])
            {
                [newDevRoom.devices addObject:dev];
                continue;
            }
            NSString *devRoomName = [dev getRoomName];
            if (devRoomName.length == 0) {
                continue;
            }
            BOOL isFind = false;
            for (RoomModel *model in roomDevLists) {
                if ([model.name isEqualToString:devRoomName]) {
                    [model.devices addObject:dev];
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                RoomModel *room = [[RoomModel alloc]initWithTitle:devRoomName];
                [room.devices addObject:dev];
                [roomDevLists addObject:room];
            }
        }
        if (newDevRoom.devices.count > 0)
        {
            [roomDevLists insertObject:newDevRoom atIndex:0];
        }
        self.m_roomModels = roomDevLists;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}

-(NSArray *) createRightButtons: (int) number
{
    NSMutableArray * result = [NSMutableArray array];
    NSArray *colors = @[RGBColor(239, 75, 58),RGBColor(204, 204, 204)];
    NSArray *icons = @[[UIImage imageNamed:@"scene_bigdel"], [UIImage imageNamed:@"scene_bigedit"]];

    for (int i = 0; i < number; ++i)
    {
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:@"" icon:icons[i] backgroundColor:colors[i] padding:15 callback:^BOOL(MGSwipeTableCell * sender){
            debugLogInfo(@"Convenience callback received (left).");
            return YES;
        }];
        [result addObject:button];
    }
    return result;
}

- (BOOL)delDev:(ZTDevice *)dev {
    BOOL result = true;
    if (dev.devType == ZTDeviceTypeLCCamera) {
        ZTLCCamera *lCCamera = (ZTLCCamera *)dev;
        result = [lCCamera unbundling];
    }
    return result;
}

#pragma mark - getters and setters
- (RTDragCellTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[RTDragCellTableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kBgColor;
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 0;
        _tableView.showsVerticalScrollIndicator = false;
        _tableView.showsHorizontalScrollIndicator = false;
        _tableView.rowHeight = 55;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [[UIView alloc]init];
    }
    return _tableView;
}
@end
